<?php



	function geturl($url, $username = null, $password = null)
	{
		if(function_exists("curl_init"))
		{
			$ch = curl_init();
			if(!is_null($username) && !is_null($password))
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Basic ' .  base64_encode("$username:$password")));
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
			$html = curl_exec($ch);
			curl_close($ch);
			return $html;
		}
		elseif(ini_get("allow_url_fopen") == true)
		{
			if(!is_null($username) && !is_null($password))
				$url = str_replace("://", "://$username:$password@", $url);
			$html = file_get_contents($url);
			return $html;
		}
		else
		{
			// Cannot open url. Either install curl-php or set allow_url_fopen = true in php.ini
			return false;
		}
	}


	/**
	 * Returns geocode localization 
	 * @return 
	 * @param $address Object
	 * @param $key Object
	 * @param $output Object[optional]
	 */
	function geocode($address, $key, $output = "xml")
	{
		$address = urlencode($address);
		$key     = urlencode($key);
		$data    = utf8_encode(geturl("http://maps.google.com/maps/geo?q=$address&key=$key&output=$output"));

		if($output == "xml")
		{
			$xml = simplexml_load_string($data);
			if($xml === false) return false;
			if($xml->Response->Status->code != "200") return false;
			return explode(",", (string) $xml->Response->Placemark->Point->coordinates);
		}
		else
			return $data;
	}


// **********



	$apiKey = "ABQIAAAADuQKsxjVmy7Sm4miTg6gXxS0qTNxOV6nIfrmHnry59ufK7qotxSfPgJ3DhXAIt2fMTar1_i7JqC-4w";

	echo "<pre>";
	print_r(geocode("el bolsón", $apiKey));
	echo "</pre>";

// turdera.dyndns.org  API key
// ABQIAAAADuQKsxjVmy7Sm4miTg6gXxS0qTNxOV6nIfrmHnry59ufK7qotxSfPgJ3DhXAIt2fMTar1_i7JqC-4w
?>
